package controller

import (
	"fileNest/dao"
	"fileNest/model"
	"fileNest/util"
	"fmt"

	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson"
)

func Register(ctx *gin.Context) {
	var req model.AuthRequest
	if err := ctx.ShouldBind(&req); err != nil {
		util.FailResponse(ctx, err)
		return
	}
	var value = bson.M{
		"username": req.UserName,
	}

	var temp interface{}
	if err := dao.DBFindOne("user", value, &temp); err != nil && err.Error() == "mongo: no documents in result" {
		hashPassWord, err := util.HashPassword(req.PassWord)
		if err != nil {
			util.FailResponse(ctx, err)
			return
		}
		value["password"] = hashPassWord
		value["auth"] = "user"
		_, err = dao.DBAdd("user", value)
		if err != nil {
			util.FailResponse(ctx, err)
			return
		}
		util.SuccessResponse(ctx, nil, "注册成功")
		return
	}
	util.FailResponse(ctx, fmt.Errorf("用户已存在"))
}

func Login(ctx *gin.Context) {
	var req model.AuthRequest
	if err := ctx.ShouldBind(&req); err != nil {
		util.FailResponse(ctx, err)
		return
	}
	query := bson.M{
		"username": req.UserName,
	}

	var data model.UserInfo

	if err := dao.DBFindOne("user", query, &data); err != nil {
		util.FailResponse(ctx, fmt.Errorf("账号不存在"))
		return
	}
	if ok := util.CheckPassWorkHash(data.PassWord, req.PassWord); ok {

		token, err := util.GenerateJWT(data)
		if err != nil {
			util.FailResponse(ctx, err)
			return
		}
		data.Token = token
		util.SuccessResponse(ctx, data, nil)
	} else {
		util.FailResponse(ctx, fmt.Errorf("密码错误"))
	}
}
